<?php

declare (strict_types=1);

namespace app\common\model\groupon;

use cores\BaseModel;
use app\common\library\helper;
use think\model\relation\HasMany;
use think\model\relation\BelongsTo;
use app\common\service\Goods as GoodsService;
use app\common\enum\groupon\ActiveType as ActiveTypeEnum;
use app\common\enum\groupon\ActiveStatus as ActiveStatusEnum;

/**
 * 拼团商品模型
 * Class Goods
 * @package app\common\model\groupon
 */
class Goods extends BaseModel
{
    // 定义表名
    protected $name = 'groupon_goods';

    // 定义主键
    protected $pk = 'groupon_goods_id';

    // 定义别名
    protected string $alias = 'groupon_goods';

    // 追加字段
    protected $append = ['active_status', 'active_sales', 'show_people'];

    /**
     * 关联模型：主商品信息
     * @return BelongsTo
     */
    public function goods(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\Goods", 'goods_id');
    }

    /**
     * 关联模型：拼团商品SKU记录
     * @return HasMany
     */
    public function skuList(): HasMany
    {
        return $this->hasMany('GoodsSku', 'groupon_goods_id')->order(['id' => 'asc']);
    }

    /**
     * 获取器：活动开始时间
     * @param $value
     * @return false|string
     */
    public function getStartTimeAttr($value)
    {
        return format_time($value);
    }

    /**
     * 获取器：活动结束时间
     * @param $value
     * @return false|string
     */
    public function getEndTimeAttr($value)
    {
        return format_time($value);
    }

    /**
     * 获取器：拼团活动状态
     * @param $value
     * @param $item
     * @return int
     */
    public function getShowPeopleAttr($value, $item): int
    {
        if ($item['active_type'] == ActiveTypeEnum::STEPS) {
            $stepsConfig = helper::jsonDecode($item['steps_config']);
            return (int)current($stepsConfig);
        }
        return $item['people'];
    }

    /**
     * 获取器：拼团活动状态
     * @param $value
     * @param $item
     * @return int
     */
    public function getActiveStatusAttr($value, $item): int
    {
        $nowTime = time();
        if ($nowTime < $item['start_time']) {
            return ActiveStatusEnum::STATE_SOON;
        }
        if ($nowTime < $item['end_time']) {
            return ActiveStatusEnum::STATE_BEGIN;
        }
        return ActiveStatusEnum::STATE_END;
    }

    /**
     * 获取器：活动销量（用户端显示）
     * @param $value
     * @param $data
     * @return false|string
     */
    public function getActiveSalesAttr($value, $data)
    {
        return $value ?: $data['actual_sales'] + $data['initial_sales'];
    }

    /**
     * 获取器：阶梯配置
     * @param string|null $json
     * @return false|array
     */
    public function getStepsConfigAttr(?string $json)
    {
        return $json ? helper::jsonDecode($json) : [];
    }

    /**
     * 设置器：阶梯配置
     * @param array $array
     * @return false|string
     */
    public function setStepsConfigAttr(array $array)
    {
        $data = array_map(function ($val) {
            return (int)$val;
        }, $array);
        return helper::jsonEncode($data);
    }

    /**
     * 拼团商品详情
     * @param int $grouponGoodsId
     * @param array $with
     * @return static|array|null
     */
    public static function detail(int $grouponGoodsId, array $with = [])
    {
        return static::get($grouponGoodsId, $with);
    }

    /**
     * 设置商品展示的数据
     * @param $data
     * @param bool $isMultiple
     * @param array $hidden
     * @param callable|null $callback
     * @return mixed
     */
    protected function setGoodsListData($data, bool $isMultiple = true, array $hidden = [], callable $callback = null)
    {
        // 设置主商品数据
        $data = GoodsService::setGoodsData($data, $isMultiple, $hidden);
        if (!$isMultiple) $dataSource = [&$data]; else $dataSource = &$data;
        // 整理商品数据
        foreach ($dataSource as &$item) {
            // 商品名称
            $item['goods_name'] = $item['goods']['goods_name'];
            // 商品图片
            $item['goods_image'] = $item['goods']['goods_image'];
            // 拼团价格
            $item['groupon_price'] = $item['groupon_price_min'];
            // 拼团商品原价 (获取主商品价格)
            $item['original_price'] = $item['goods']['goods_price_min'];
            // 回调函数
            is_callable($callback) && call_user_func($callback, $item);
        }
        return $data;
    }
}